<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller;

use buwang\base\AdminBaseController;
use app\manage\model\AuthGroupNode;
use app\manage\model\AuthGroup;
use app\manage\model\AuthNode;
use app\manage\model\AuthGroupAccess;
use app\manage\model\Member;
use app\common\model\Miniapp;
use  app\manage\model\admin\Plugin;
class Role extends AdminBaseController
{
    /**
     * 查看
     * @menu true
     */
    public function index()
    {

        if (request()->isPost() || request()->isAjax()) {


            $list = AuthGroupNode::getlist([['scopes', '=', 'admin']]);

            $count = count($list);
            //var_dump($list);die;
            $list = array_merge(AuthNode::tree($list, 'name', 'id'));

            return json([
                'code' => 0,
                'msg' => '查询成功',
                'count' => $count,
                'data' => $list,
            ]);

        }
        $miniapp = Miniapp::select()->toArray();
        return view('', ['miniapp' => $miniapp]);
    }

    /**
     * 查看租户角色
     * @menu true
     */
    public function memberRole()
    {
        $member_id = $this->request->get('member_id');
        if (request()->isPost() || request()->isAjax()) {

            $Member = Member::getTop($member_id);
            $list = AuthGroupNode::getMemberlist([['scopes', '=', 'member'], ['member_id', '=', $Member['id']]], $Member['id']);

            $count = count($list);
            //var_dump($list);die;
            $list = array_merge(AuthNode::tree($list, 'name', 'id'));

            return json([
                'code' => 0,
                'msg' => '查询成功',
                'count' => $count,
                'data' => $list,
            ]);

        }
        return view('', ['member_id' => $member_id]);
    }

    /**
     * 应用模块角色
     * @menu true
     */
    public function modelRole()
    {
        if (request()->isPost() || request()->isAjax()) {
            $miniapp_id = $this->request->get('miniapp_id') ?: 0;//应用id

            $list = AuthGroupNode::getMeberlist([['scopes', '=', 'member'], ['member_id', '=', 0]], $miniapp_id);

            $count = count($list);
            //var_dump($list);die;
            $list = array_merge(AuthNode::tree($list, 'name', 'id'));

            return json([
                'code' => 0,
                'msg' => '查询成功',
                'count' => $count,
                'data' => $list,
            ]);
        }
    }

    /**
     * 编辑管理组
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $topAdminRoleId = config('auth.super_admin_role_id');//超级管理员角色
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //父级不能是自己
            if (isset($param['pid'])) {
                if ($param['pid'] == $param['id']) {
                    return $this->error('父ID不能是自己');
                }
            }
            if (isset($param['group_name'])) {
                //判断是否存在唯一标识
                $count = AuthGroup::where('group_name', $param['group_name'])->where('id', 'not in', $param['id'])->count();
                if ($count) return $this->error('已存在该标识');
            }
            if (isset($param['name'])) {
                //判断是否存在唯一标识
                $count = AuthGroup::where('name', $param['name'])->where('id', 'not in', $param['id'])->count();
                if ($count) return $this->error('已存在该用户组名');
            }
            $res = AuthGroupNode::updateRule($param['id'], explode(",", $param['rule_ids']), true);
            if (!$res) return $this->error(AuthGroupNode::getError('操作失败'));

            $result = AuthGroup::update($param);
            //编辑中间表
            $AuthGroupNodes = AuthGroupAccess::where('group_id', $param['id'])->select()->toArray();
            if ($AuthGroupNodes) {
                $AuthGroup_data = array();
                foreach ($AuthGroupNodes as $AuthGroupNode) {
                    $GroupNode = array();
                    $GroupNode ['id'] = $AuthGroupNode['id'];
                    if (isset($param['name'])) {
                        $GroupNode['name'] = $param['name'];
                    }


                    $AuthGroup_data[] = $GroupNode;
                }
                $AuthGroupNode = new AuthGroupAccess;
                $AuthGroupNode->saveAll($AuthGroup_data);
            }
            if ($result) {
                //xn_add_admin_log('修改管理组名称');
                return $this->success('操作成功');
            } else {
                return $this->error('操作失败');
            }
        }
        $id = $this->request->get('id');
        $data = AuthGroup::find($id);
        $data['rule_ids'] = null;
        //查询所有权限，以逗号拼接
        $rules = AuthGroupNode::valiWhere()->where('group_id', $id)->column('node_id');
        if ($rules) $data['rule_ids'] = implode(",", $rules);
        return view('form', ['data' => $data, 'pid' => $data['pid'], 'super_admin_role_id' => $topAdminRoleId]);
    }

    /**
     * 编辑管理组
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editModel()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //父级不能是自己
            if (isset($param['pid'])) {
                if ($param['pid'] == $param['id']) {
                    return $this->error('父ID不能是自己');
                }
            }
            if (isset($param['group_name'])) {
                //判断是否存在唯一标识
                $count = AuthGroup::where('group_name', $param['group_name'])->where('id', 'not in', $param['id'])->count();
                if ($count) return $this->error('已存在该标识');
            }
            if (isset($param['name'])) {
                //判断是否存在唯一标识
                $count = AuthGroup::where('name', $param['name'])->where('scopes', 'member')->where('member_id', 0)->where('id', 'not in', $param['id'])->count();
                if ($count) return $this->error('已存在该用户组名');
            }
            $res = AuthGroupNode::updateRule($param['id'], explode(",", $param['rule_ids']), true);
            if (!$res) return $this->error(AuthGroupNode::getError('操作失败'));

            $result = AuthGroup::update($param);
            //编辑中间表
            $AuthGroupNodes = AuthGroupAccess::where('group_id', $param['id'])->select()->toArray();
            if ($AuthGroupNodes) {
                $AuthGroup_data = array();
                foreach ($AuthGroupNodes as $AuthGroupNode) {
                    $GroupNode = array();
                    $GroupNode ['id'] = $AuthGroupNode['id'];
                    if (isset($param['name'])) {
                        $GroupNode['name'] = $param['name'];
                    }


                    $AuthGroup_data[] = $GroupNode;
                }
                $AuthGroupNode = new AuthGroupAccess;
                $AuthGroupNode->saveAll($AuthGroup_data);
            }
            if ($result) {
                return $this->success('操作成功');
            } else {
                return $this->error('操作失败');
            }
        }
        $id = $this->request->get('id');
        $data = AuthGroup::find($id);
        $data['rule_ids'] = null;
        //查询所有权限，以逗号拼接
        $rules = AuthGroupNode::valiWhere()->where('group_id', $id)->column('node_id');
        if ($rules) $data['rule_ids'] = implode(",", $rules);
        $miniapp = Miniapp::select()->toArray();
        $plugin = Plugin::select()->toArray();
        // var_dump($list);die;
        return view('form_model', ['data' => $data, 'pid' => $data['pid'],'miniapp'=>$miniapp,'plugin'=>$plugin]);
    }

    /**
     * 添加管理组
     * @return \think\Response
     */
    public function add()
    {
        $topAdminRoleId = config('auth.super_admin_role_id');//超级管理员角色
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //判断是否存在唯一标识
            $count = AuthGroup::where('group_name', $param['group_name'])->count();
            if ($count) return $this->error('已存在该标识');
            $count = AuthGroup::where('name', $param['name'])->count();
            if ($count) return $this->error('已存在该用户组名');
            $result = new AuthGroup;
            $result['group_name'] = $param['group_name'];
            $result['name'] = $param['name'];
            $result['pid'] = $param['pid'];
            $result['status'] = $param['status'];
            $result->save();
            if (!$result) return $this->error('操作失败');
            $res = AuthGroupNode::updateRule($result['id'], explode(",", $param['rule_ids']), false);
            if (!$res) return $this->error(AuthGroupNode::getError('操作失败'));
            return $this->success('操作成功');

        }
        $list = AuthGroup::where('scopes', 'admin')->select()->toArray();
        $list = AuthNode::tree($list, 'name', 'id');
        return view('form', ['list' => $list, 'pid' => $this->request->get('pid'), 'super_admin_role_id' => $topAdminRoleId])->filter(function ($content) {
            return str_replace("&amp;emsp;", '&emsp;', $content);
        });
    }

    /**
     * 添加模块组
     * @return \think\response\View
     */
    public function addModel()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //判断是否存在唯一标识
            $count = AuthGroup::where('group_name', $param['group_name'])->count();
            if ($count) return $this->error('已存在该标识');
            $count = AuthGroup::where('name', $param['name'])->where('scopes', 'member')->where('member_id', 0)->count();
            if ($count) return $this->error('已存在该用户组名');
            $result = new AuthGroup;
            $result['group_name'] = $param['group_name'];
            $result['scopes'] = 'member';
            $result['member_id'] = 0;
            $result['app_name'] = $param['app_name'];
            $result['type'] = $param['type'];
            $result['name'] = $param['name'];
            $result['pid'] = $param['pid'];
            $result['status'] = $param['status'];
            $result->save();
//            $result = AuthGroup::create($param);
            if (!$result) return $this->error('操作失败');
            $res = AuthGroupNode::updateRule($result['id'], explode(",", $param['rule_ids']), false);

            if (!$res) return $this->error(AuthGroupNode::getError('操作失败'));
            // xn_add_admin_log('添加管理组');
            return $this->success('操作成功');

        }
        $list = AuthGroup::where('scopes', 'member')->where('member_id', 0)->select()->toArray();
        $list = AuthNode::tree($list, 'name', 'id');
        $miniapp = Miniapp::select()->toArray();
        $plugin = Plugin::select()->toArray();

        return view('form_model', ['list' => $list, 'pid' => $this->request->get('pid'),'miniapp'=>$miniapp,'plugin'=>$plugin])->filter(function ($content) {
            return str_replace("&amp;emsp;", '&emsp;', $content);
        });
    }

    /**
     * 删除用户组
     */
    public function delete($ids = 0)
    {
        if (request()->isPost()) {
            if (!$ids) return $this->error('参数有误');
            $list = AuthGroup::where('id', 'in', $ids)->select();
            if (!$list) return $this->error('记录不存在');
            if (in_array(1, explode(",", $ids))) return $this->error('无法删除默认用户组');

            try {
                $data = array();
                foreach ($list as $item) {

                    $child_count = AuthGroup::where('pid', $item['id'])->count();
                    if ($child_count) return $this->error('请先删除子角色组');

                    AuthGroup::destroy($item['id']);
                    //删除角色权限中间表
                    $ids = AuthGroupNode::where('group_id', $item['id'])->column('id');
                    if ($ids) {
                        AuthGroupNode::destroy($ids);
                    }
                    //删除用户角色中间表
                    $ids = AuthGroupAccess::where('group_id', $item['id'])->column('id');
                    if ($ids) {
                        AuthGroupAccess::destroy($ids);
                    }
                }
            } catch (\Exception $e) {

                return $this->error('删除失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success('删除成功');
        }
    }


//    /**
//     * 分配权限
//     * @return \think\response\View
//     * @throws \think\db\exception\DataNotFoundException
//     * @throws \think\db\exception\DbException
//     * @throws \think\db\exception\ModelNotFoundException
//     */
//    public function groupRule()
//    {
//        if ($this->request->isPost()) {
//            $param = $this->request->param();
//            if (!isset($param['rule_ids'])) $param['rule_ids'] = [];
//            $res = AuthGroupNode::updateRule($param['id'], $param['rule_ids'], true);
//            if (!$res) return $this->error(AuthGroupNode::getError('操作失败'));
//            else return $this->success('操作成功');
//        }
//
//        $id = $this->request->get('id');
//        // 获取用户组数据
//        $group_data = AuthGroupNode::getFind($id);
//
//        $group_data['rules'] = explode(',', $group_data['rules']);
//        // 获取规则数据
//        $auth_data = AuthNode::where('scopes', 'admin')->select()->toArray();
//
//        $rule_data = AuthNode::channelLevel($auth_data, 0, '&nbsp;', 'id');
//        //var_dump($rule_data);die;//常用函数
//        return view('', ['group_data' => $group_data, 'rule_data' => $rule_data]);
//    }

//    /**
//     * 排序
//     */
//    public function sort()
//    {
//        $param = $this->request->post();
//
//
//        foreach ($param as $k => $v) {
//            $v = empty($v) ? null : $v;
//            if (!$v) $v = 0;
//            AuthGroup::where('id', $k)->save(['sort' => $v]);
//        }
//        return redirect('/manage/role/index');
//    }


    /**
     * 得到用户组数据
     */
    public function getRoleTree()
    {
        $checked_ids = $this->request->param('checked_ids') ?: [];//初始化商品分类
        $disabled = $this->request->param('disabled') !== null ? $this->request->param('disabled') : true;//节点禁选
        $is_child = $this->request->param('is_child') ?: false;//是否只初始选中子节点
        if ($disabled === 'false') $disabled = false;
        if ($disabled === 'true') $disabled = true;
        if ($is_child === 'false') $is_child = false;
        if ($is_child === 'true') $is_child = true;
        return json(AuthGroup::getTree(['scopes' => 'admin'], 0, $checked_ids, $disabled, $is_child));
    }

    /**
     * 得到应用功能模块数据
     */
    public function getRoleModelTree()
    {
        $checked_ids = $this->request->param('checked_ids') ?: [];//初始化商品分类
        $disabled = $this->request->param('disabled') !== null ? $this->request->param('disabled') : true;//节点禁选
        $is_child = $this->request->param('is_child') ?: false;//是否只初始选中子节点
        if ($disabled === 'false') $disabled = false;
        if ($disabled === 'true') $disabled = true;
        if ($is_child === 'false') $is_child = false;
        if ($is_child === 'true') $is_child = true;
        return json(AuthGroup::getTree([['scopes', '=', 'member'], ['member_id', '=', 0]], 0, $checked_ids, $disabled, $is_child));
    }

    /**
     * 得到该租户的角色
     */
    public function getRoleMemberTree()
    {
        $member_id = $this->request->param('member_id') ?: 0;//租户id
        //得到顶级租户
        $Member = Member::getTop($member_id);
        //var_dump($member_id);die;
        $checked_ids = $this->request->param('checked_ids') ?: [];//初始化商品分类
        $is_customize = $this->request->param('is_customize') ?: false;//只得到自定义角色
        $disabled = $this->request->param('disabled') !== null ? $this->request->param('disabled') : true;//节点禁选
        $is_child = $this->request->param('is_child') ?: false;//是否只初始选中子节点
        if ($disabled === 'false') $disabled = false;
        if ($disabled === 'true') $disabled = true;
        if ($is_child === 'false') $is_child = false;
        if ($is_child === 'true') $is_child = true;
        if ($is_customize === 'false') $is_customize = false;
        if ($is_customize === 'true') $is_customize = true;
        $self = new AuthGroup;
        if ($Member) {
            if ($is_customize) {
                $self = $self->where('member_id', '=', $Member['id']);
            } else {
                if ($Member['id'] == $member_id) {
                    $self = $self->where('member_id', '=', 0);
                } else {
                    $self = $self->where('member_id', '=', $Member['id']);
                }
            }
        } else {
            $self = $self->where('member_id', '=', 0);
        }
        $self = $self->where('scopes', '=', 'member');
        return json(AuthGroup::getTree([], 0, $checked_ids, $disabled, $is_child, $self));
    }


    /**
     * 得到顶级租户拥有的全部节点数据
     */
    public function getNodeTree()
    {
        $member_id = $this->request->param('member_id') ?: 0;//租户id
        $Member = Member::getTop($member_id);
        $pid = $this->request->param('pid') ?: 0;//父角色
        $checked_ids = $this->request->param('checked_ids') ?: [];//初始化商品分类
        $disabled = $this->request->param('disabled') !== null ? $this->request->param('disabled') : true;//节点禁选
        $is_child = $this->request->param('is_child') ?: false;//是否只初始选中子节点

        if ($disabled === 'false') $disabled = false;
        if ($disabled === 'true') $disabled = true;
        if (!$pid) {

            //得到拥有的系统角色
            //查询中间表得到拥有的全部角色
            $SystemGroupIds = AuthGroupAccess::valiWhere()->where('uid', $Member['id'])->where('scopes', 'member')->column('group_id');
            //过滤得到系统角色 （可注释掉不过滤）
            if ($SystemGroupIds) $SystemGroupIds = AuthGroup::valiWhere()->where('id', 'in', $SystemGroupIds)->where('status', 1)->where('member_id', 0)->where('scopes', 'member')->column('id');
            //查询角色拥有的所有权限
            $NodeIds = AuthGroupNode::where('group_id', 'in', $SystemGroupIds)->column('node_id');
            return json(AuthNode::getTree([['id', 'in', $NodeIds]], 0, $checked_ids, $disabled, $is_child));

        } else {
            $NodeIds = AuthGroupNode::where('group_id', 'in', (string)$pid)->column('node_id');
            return json(AuthNode::getTree([['id', 'in', $NodeIds]], 0, $checked_ids, $disabled, $is_child));
        }

    }


    /**
     * 更改开启状态
     *
     * @return \think\Response
     */
    public function setStatus()
    {
        if (request()->isAjax()) {
            $id = input('id/d');
            $data = AuthGroup::find($id);
            if ($data['status'] === 0) {
                $data['status'] = 1;
            } elseif ($data['status'] === 1) {
                $data['status'] = 0;
            };
            $data->save();
            return $this->success('successful');

        }
    }


    /**
     * 编辑管理组
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editMember()
    {

        $member_id = $this->request->get('member_id');

        $Member = Member::getTop($member_id);
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //父级不能是自己
            if (isset($param['pid'])) {
                if ($param['pid'] == $param['id']) {
                    return $this->error('父ID不能是自己');
                }
            }
            if (isset($param['group_name'])) {
                //判断是否存在唯一标识
                $count = AuthGroup::where('group_name', $param['group_name'])->where('id', 'not in', $param['id'])->count();
                if ($count) return $this->error('请换一个标识，该标识有人在使用');
            }
            if (isset($param['name'])) {
                //判断是否存在唯一标识
                $count = AuthGroup::where('name', $param['name'])->where('scopes', 'member')->where('member_id', '<>', 0)->where('id', 'not in', $param['id'])->count();
                if ($count) return $this->error('已存在该用户组名');
            }
            $res = AuthGroupNode::updateRule($param['id'], explode(",", $param['rule_ids']), true);
            if (!$res) return $this->error(AuthGroupNode::getError('操作失败'));

            $result = AuthGroup::update($param);
            //编辑中间表
            $AuthGroupNodes = AuthGroupAccess::where('group_id', $param['id'])->select()->toArray();
            if ($AuthGroupNodes) {
                $AuthGroup_data = array();
                foreach ($AuthGroupNodes as $AuthGroupNode) {
                    $GroupNode = array();
                    $GroupNode ['id'] = $AuthGroupNode['id'];
                    if (isset($param['name'])) {
                        $GroupNode['name'] = $param['name'];
                    }


                    $AuthGroup_data[] = $GroupNode;
                }
                $AuthGroupNode = new AuthGroupAccess;
                $AuthGroupNode->saveAll($AuthGroup_data);
            }
            if ($result) {
                //xn_add_admin_log('修改管理组名称');
                return $this->success('操作成功');
            } else {
                return $this->error('操作失败');
            }
        }
        $id = $this->request->get('id');
        $data = AuthGroup::find($id);
        $data['rule_ids'] = null;
        //查询所有权限，以逗号拼接
        $rules = AuthGroupNode::valiWhere()->where('group_id', $id)->column('node_id');
        if ($rules) $data['rule_ids'] = implode(",", $rules);

        // var_dump($list);die;
        return view('form_member', ['data' => $data, 'pid' => $data['pid'], 'member_id' => $member_id]);
    }


    /**
     * 添加管理组
     * @return \think\response\View
     */
    public function addMember()
    {
        $member_id = $this->request->get('member_id');

        $Member = Member::getTop($member_id);

        if ($this->request->isPost()) {
            $param = $this->request->param();
            //判断是否存在唯一标识
            $count = AuthGroup::where('group_name', $param['group_name'])->count();
            if ($count) return $this->error('请换一个标识，该标识有人在使用');
            $count = AuthGroup::where('name', $param['name'])->where('scopes', 'member')->where('member_id', '<>', 0)->count();
            if ($count) return $this->error('已存在该用户组名');
            $result = new AuthGroup;
            $result['group_name'] = $param['group_name'];
            $result['name'] = $param['name'];
            $result['pid'] = $param['pid'];
            $result['status'] = $param['status'];
            $result['scopes'] = 'member';
            $result['member_id'] = $Member['id'];
            $result->save();
//            $result = AuthGroup::create($param);
            if (!$result) return $this->error('操作失败');
            $res = AuthGroupNode::updateRule($result['id'], explode(",", $param['rule_ids']), false);

            if (!$res) return $this->error(AuthGroupNode::getError('操作失败'));
            // xn_add_admin_log('添加管理组');
            return $this->success('操作成功');

        }
        $list = AuthGroup::where('scopes', 'member')->where('member_id', '<>', 0)->select()->toArray();
        $list = AuthNode::tree($list, 'name', 'id');
        return view('form_member', ['list' => $list, 'pid' => $this->request->get('pid'), 'member_id' => $member_id])->filter(function ($content) {
            return str_replace("&amp;emsp;", '&emsp;', $content);
        });
    }


}
